from functools import wraps
from threading import Timer

# 时间单位秒
def debounce(idle: float):
    def wrapped(fn):
        timer = None
        cache_args = ()
        cache_kwargs = {}

        def call():
            nonlocal timer
            timer = None
            fn(*cache_args, **cache_kwargs)

        @wraps(fn)
        def _fn(*args, **kwargs):
            nonlocal timer, cache_args, cache_kwargs
            cache_args, cache_kwargs = args, kwargs
            if timer is not None and timer.is_alive():
                timer.cancel()
            timer = Timer(idle, call)
            timer.start()

        return _fn

    return wrapped
